package com.hdl.script.ui.activity

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.hdl.script.R
import com.hdl.script.logic.view.ScriptViewModel
import com.hdl.script.model.Script
import com.hdl.script.ui.adapter.ScriptAdapter
import com.hdl.script.ui.decoration.HorizontalDividerItemDecoration
import com.hdl.script.ui.decoration.VerticalDividerItemDecoration
import kotlinx.android.synthetic.main.activity_main.toolbar
import kotlinx.android.synthetic.main.activity_script_recycle.*

class ScriptRecyclerActivity : AppCompatActivity(), Observer<MutableList<Script>> {

    private val mScriptAdapter: ScriptAdapter by lazy {
        ScriptAdapter(this)
    }
    private var mScriptViewModel: ScriptViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_script_recycle)
        initView()
    }

    private fun initView() {
        setSupportActionBar(toolbar)
        scriptRecycler.layoutManager = LinearLayoutManager(this)
        scriptRecycler.adapter = mScriptAdapter
        scriptRecycler.addItemDecoration(HorizontalDividerItemDecoration.Builder(this)
                .colorResId(android.R.color.black).size(2).build())
        mScriptViewModel = ViewModelProvider(this).get(ScriptViewModel::class.java)
        mScriptViewModel?.getScriptData()?.observe(this, this)
        mScriptViewModel?.searchFile(this)
    }

    override fun onDestroy() {
        mScriptViewModel?.getScriptData()?.removeObserver(this)
        super.onDestroy()
    }

    override fun onChanged(it: MutableList<Script>?) {
        if (it?.isNotEmpty() == true) {
            mScriptAdapter.clearData()
            mScriptAdapter.addAll(it)
            mScriptAdapter.notifyDataSetChanged()
        }
    }

}